package com.example.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.entity.Goods;
import com.example.entity.OrderMessage;
import com.example.mapper.GoodsMapper;
import com.example.service.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class GoodsServiceImpl extends ServiceImpl<GoodsMapper, Goods> implements GoodsService {

    @Autowired
    private GoodsService goodsService;

    /**
     * 库存减操作
     */
    @Override
    @Transactional
    public Boolean deleteShopping(List<OrderMessage> orderMessage) {
        List<Long> ids = orderMessage.stream().map(OrderMessage::getGoodsId).collect(Collectors.toList());
        List<Goods> goodsList = goodsService.list(Wrappers.<Goods>lambdaQuery().in(Goods::getId, ids));
        for (Integer i = 0; i < goodsList.size(); i++) {
            Goods goods = goodsList.get(i);
            Integer orderAmount = orderMessage.get(i).getOrderAmount();
            if (goods.getInventory() < orderAmount) {
                return false;
            }
            goods.setInventory(goods.getInventory() - orderAmount);
            goods.setOrderNum(goods.getOrderNum() + orderAmount);
        }
        return goodsService.updateBatchById(goodsList);
    }

}
